import { browser } from '@/utils/http'
import Konva from 'konva'
import { ERecorderBrashColor } from './index'
import { EDotDrawingToolName, EDrawingToolName, hPxRatio, wPxRatio } from './boardProperty'
import { Shape, ShapeConfig } from 'konva/lib/Shape'
import svgUrl from '@/assets/images/home/close.svg'
import { Group } from 'konva/lib/Group'
import { IImageToolManage } from './image'

/**初始化画板 */
export const initBoard = (
  context: IImageToolManage,
  stage: Konva.Stage,
  layers: Array<Konva.Shape | Konva.Layer>,
) => {
  /**选择对象 */
  stage.on('click', (evt: any) => {
    const shape = evt.target as Konva.Shape
    stage.find(EDotDrawingToolName.Dotrotatetransform).forEach((node) => node.remove())
    stage.find(EDotDrawingToolName.DotrotatetransformLayer).forEach((node) => node.remove())
    stage.find(EDotDrawingToolName.DotcloseShapebtn).forEach((node) => node.remove())
    /**取消拖拽状态 */
    if (shape.name() == EDrawingToolName.BgRect) {
      if (shape.draggable()) {
        shape.draggable(false)
      }
      context.activeShape = null
      return
    }
    if (shape.name() == EDrawingToolName.CloseShapebtn) {
      stage.find(EDotDrawingToolName.Dotrotatetransform).forEach((node) => node.remove())
      const idx = layers.findIndex((node) => node.name() === context.activeShape?.name())
      layers.splice(idx, 1)
      context.activeShape?.remove()
      shape.remove()
    }
    if (
      shape &&
      shape.parent &&
      shape.parent.name() != EDrawingToolName.Rotatetransform &&
      shape.name() != EDrawingToolName.Rotatetransform
    ) {
      context.activeShape = shape
      if (!shape.draggable()) {
        shape.draggable(true)
      }
      const layer = new Konva.Layer({ name: EDrawingToolName.RotatetransformLayer })
      const transform = new Konva.Transformer({
        nodes: [shape],
        centeredScaling: true,
        rotationSnaps: [0, 90, 180, 270],
        resizeEnabled: true,
        name: EDrawingToolName.Rotatetransform,
      })

      /**关闭按钮 */
      Konva.Image.fromURL(svgUrl, (imageNode: Shape<ShapeConfig> | Group) => {
        imageNode.setAttrs({
          name: EDrawingToolName.CloseShapebtn,
          x: -15,
          y: -40,
          width: 30,
          height: 30,
        })
        transform.add(imageNode)
      })

      layer.add(transform)
      stage.add(layer)
    }
  })
  //拖拽初始化
  const con = stage.container()
  /**拖拽 贴图*/
  con.addEventListener('dragover', function (e) {
    e.preventDefault()
  })

  con.addEventListener('drop', (e: any) => {
    e.preventDefault()
    stage.setPointersPositions(e)
    if (!e.dataTransfer.getData('Text')) {
      return ''
    }
    const data: { url: string } = JSON.parse(e.dataTransfer.getData('Text'))
    Konva.Image.fromURL(data.url, (image: Konva.Image) => {
      const layer = new Konva.Layer()
      layer.add(image)
      image.position(stage.getPointerPosition()!)
      image.draggable(true)
    })
  })
}
